import os

from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import (QMainWindow, QWidget, QGridLayout, QLabel,
                             QLineEdit, QPushButton, QFileDialog, QMessageBox,
                             QCheckBox, QSpacerItem, QSizePolicy, QSystemTrayIcon, QAction)
from PyQt5.QtCore import Qt
from src.core.paramsHandler import ParamsHandler


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("XMind转TestCase工具")
        self.setFixedSize(600, 450)
        # 设置窗口图标
        self._set_window_icon()
        self._setup_ui()

    def _set_window_icon(self):
        # 图片路径（请根据实际路径修改）
        icon_path = os.path.join(os.path.dirname(__file__), '../../resources/', 'logo2.ico')
        # 设置窗口图标
        self.setWindowIcon(QIcon(icon_path))
        # 确保ICO文件存在
        if os.path.exists(icon_path):
            self.setWindowIcon(QIcon(icon_path))
        else:
            print(f"图标文件未找到：{icon_path}")

    def _setup_ui(self):
        central_widget = QWidget()
        self.setCentralWidget(central_widget)

        main_layout = QGridLayout()
        central_widget.setLayout(main_layout)
        main_layout.setVerticalSpacing(15)
        main_layout.setHorizontalSpacing(10)

        # 文件选择区域
        self._setup_file_selection(main_layout)

        # 参数设置区域
        self._setup_parameters(main_layout)

        # 选项区域
        self._setup_options(main_layout)

        # 转换按钮
        self._setup_convert_button(main_layout)

        # 版权信息区域
        self._setup_copyright_info(main_layout)

        # 添加菜单栏
        self._setup_menu()

    def _setup_menu(self):
        # 创建菜单栏
        menu_bar = self.menuBar()

        # 创建“帮助”菜单
        help_menu = menu_bar.addMenu("帮助")

        # 创建“关于”菜单项
        about_action = QAction("关于", self)
        about_action.triggered.connect(self.show_about_dialog)
        help_menu.addAction(about_action)

    def show_about_dialog(self):
        # 创建“关于”对话框
        about_message = """Copyright © Mr.L. All Rights Reserved.\nContact: xiaoyan_lu2021@163.com\nProject Name: XMind转TestCase工具\nThis software is licensed under the MIT License. See LICENSE file for more details."""

        QMessageBox.information(self, "关于", about_message)

    def _setup_copyright_info(self, layout):
        # 添加版权信息
        copyright_label = QLabel("Copyright © Mr.L. All Rights Reserved.")
        copyright_label.setAlignment(Qt.AlignCenter)
        layout.addItem(QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding), 9, 0)
        layout.addWidget(copyright_label, 10, 0, 1, 3, alignment=Qt.AlignCenter)

    def _setup_file_selection(self, layout):
        # XMind文件选择
        layout.addWidget(QLabel("XMind文件:"), 0, 0, Qt.AlignRight)
        self.input_path = QLineEdit()
        self.input_path.setMinimumWidth(350)
        input_btn = QPushButton("浏览...")
        input_btn.setFixedWidth(80)
        input_btn.clicked.connect(self._select_input_file)
        layout.addWidget(self.input_path, 0, 1)
        layout.addWidget(input_btn, 0, 2)

        # Excel输出
        layout.addWidget(QLabel("Excel输出:"), 1, 0, Qt.AlignRight)
        self.excel_path = QLineEdit()
        excel_btn = QPushButton("浏览...")
        excel_btn.setFixedWidth(80)
        excel_btn.clicked.connect(lambda: self._select_output_file(self.excel_path, "Excel文件 (*.xlsx)"))
        layout.addWidget(self.excel_path, 1, 1)
        layout.addWidget(excel_btn, 1, 2)

        # Word输出
        layout.addWidget(QLabel("Word输出:"), 2, 0, Qt.AlignRight)
        self.word_path = QLineEdit()
        word_btn = QPushButton("浏览...")
        word_btn.setFixedWidth(80)
        word_btn.clicked.connect(lambda: self._select_output_file(self.word_path, "Word文件 (*.docx)"))
        layout.addWidget(self.word_path, 2, 1)
        layout.addWidget(word_btn, 2, 2)

    def _setup_parameters(self, layout):
        # 第一步参数
        layout.addWidget(QLabel("第一步:"), 3, 0, Qt.AlignRight)
        self.first_step_input = QLineEdit("打开软件")
        self.first_step_input.setMinimumWidth(350)
        layout.addWidget(self.first_step_input, 3, 1, 1, 2)

        # 第二步前缀
        layout.addWidget(QLabel("第二步前缀:"), 4, 0, Qt.AlignRight)
        self.second_prefix_input = QLineEdit("点击")
        layout.addWidget(self.second_prefix_input, 4, 1, 1, 2)

        #前提条件
        layout.addWidget(QLabel("前提条件:"), 5, 0, Qt.AlignRight)
        self.precondition_input = QLineEdit("系统测试环境搭建完毕且运行正常、连接硬件且硬件无故障")
        layout.addWidget(self.precondition_input, 5, 1, 1, 2)

        #测试点
        layout.addWidget(QLabel("测试点:"), 6, 0, Qt.AlignRight)
        self.test_point_input = QLineEdit("测试xxxxx是否正常")
        layout.addWidget(self.test_point_input, 6, 1, 1, 2)

    def _setup_options(self, layout):
        # 自动打开选项
        self.excel_checkbox = QCheckBox("自动打开Excel")
        self.word_checkbox = QCheckBox("自动打开Word")
        self.word_checkbox.setChecked(True)

        layout.addWidget(self.excel_checkbox, 7, 1)
        layout.addWidget(self.word_checkbox, 7, 2)

    def _setup_convert_button(self, layout):
        # 转换按钮
        convert_btn = QPushButton("开始转换")
        convert_btn.setFixedWidth(150)
        layout.addItem(QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding), 8, 0)
        layout.addWidget(convert_btn, 8, 1, 1, 2, alignment=Qt.AlignCenter)
        convert_btn.clicked.connect(self._convert)

    def _select_input_file(self):
        path, _ = QFileDialog.getOpenFileName(
            self, "选择XMind文件", "", "XMind文件 (*.xmind)")
        if path:
            self.input_path.setText(path)
            base_path = os.path.splitext(path)[0]
            if not self.excel_path.text():
                self.excel_path.setText(f"{base_path}.xlsx")
            if not self.word_path.text():
                self.word_path.setText(f"{base_path}.docx")

    def _select_output_file(self, target_field, file_filter):
        path, _ = QFileDialog.getSaveFileName(
            self, "保存文件", "", file_filter)
        if path:
            target_field.setText(path)

    def _convert(self):
        if not self.input_path.text():
            QMessageBox.warning(self, "警告", "请选择XMind文件")
            return

        try:
            success, message = ParamsHandler.control_handler(
                self.input_path.text(),
                self.excel_path.text(),
                self.word_path.text(),
                first_step=self.first_step_input.text().strip() or None,
                second_prefix=self.second_prefix_input.text().strip() or None,
                precondition_input = self.precondition_input.text().strip() or None,
                test_point_input = self.test_point_input.text().strip() or None,
                open_excel=self.excel_checkbox.isChecked(),
                open_word=self.word_checkbox.isChecked()
            )

            if success:
                QMessageBox.information(self, "成功", message)
            else:
                QMessageBox.critical(self, "错误", message)
        except Exception as e:
            QMessageBox.critical(self, "异常错误", f"转换过程中发生异常: {str(e)}")
